import axios from 'axios'
import store from './../store'
import { ElMessage } from 'element-plus'
import router from '../router'
export const request = axios.create({
  // baseURL: 'http://8.133.252.78',
  baseURL: '',
})


// 请求拦截器
request.interceptors.request.use(
    config => {
        // 在发送请求之前做些什么，比如添加 token
        const token = store.state.token || localStorage.getItem('token');
        if (token) {
            // 动态添加 Authorization 头
            config.headers['Authorization'] = 'Bearer ' + token;
        }
        return config;
    },
    error => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

request.interceptors.response.use(
  response => {
    if (response.config.responseType == 'blob') {
      if (response.status == 200) {
        return response.data
      } else {
        ElMessage.error({
          duration: 3000,
          message: '下载失败'
        })
        return
      }
    }
    if (response.data.code == 200) {
      return response.data
    } else {
      ElMessage({
        type: 'error',
        duration: 3000,
        message: response.data.message
      })
    }
  },
  error => {
      if (error.response.status === 403){
          console.log('store.state.token',store.state.token)
          router.push({ path: '/',query:{id:0} })
      }
    return Promise.reject(error)
  }
)
